import React from 'react';
import {Select, Form, Row, Col, Input, Button, DatePicker, Icon} from 'antd';
import axios from 'axios';
import {startTypeJSON} from '../../utils/tranStartType';
import moment from 'moment';
import { injectIntl } from 'react-intl';
import {sessionManager} from '../../utils/sessionStorage';
import StubPicker from '../../components/pickCity/StubPicker';
import qs from 'qs'
import DepartmentPicker from '../../components/pickCity/departmentPicker';
import SCSelect from '../../components/pickCity/SCSelect'


const Option = Select.Option;
const RangePicker = DatePicker.RangePicker;
const FormItem = Form.Item;
const createForm = Form.create;

class innerEnterpriseForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            stubGroup: [],
            orderSummary: {},
            searchQuest: "",
            hideFlag:true
        };
        this.formItem = null;
        this.lessXXl=window.innerWidth< 1600;
    }

    endTimeLess = (rule, value, callback) => {
        let startTime;
        let endTime;
        let differDay;
        if (value && value.length > 0) {
            startTime = value[0].format('x');
            endTime = value[1].format('x');
            differDay = ((endTime - startTime) / 1000 / 60 / 60 / 24);
        }
        if (differDay > 10) {
            callback('相距不能超过10天');
        } else {
            callback();
        }
    }
    //清空表格
    handleReset = () => {
        const {setFieldsValue}=this.props.form;
        this.props.form.resetFields();
        setFieldsValue({
            "validFlag":undefined
        })
    }

    obj2getParam = (values) => {
        var params = ``;
        for (let key of Object.keys(values)) {
            if (values[key]) {
                console.log(key, values[key]);
                params += `${key}=${values[key]}&`
            }
        }
        this.setState({
            searchQuest: params
        })
        console.log(params)
    }

    //提交表格验证
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((errors, values) => {
            if (!!errors) {
                console.log('Errors in form!!!');
                return;
            }
            console.log('Submit!!!');
            let data = {
                qryType: 1,
            };
            if (values.chargeStartTime.length != 0) {
                data.chargeEndTimeStart = values.chargeStartTime[0].format('YYYY.MM.DD HH:mm:ss');
                data.chargeEndTimeEnd = values.chargeStartTime[1].format('YYYY.MM.DD HH:mm:ss');
            }
            delete values['chargeStartTime'];
            delete values['chargeEndTime'];
            Object.assign(values, data);
            this.obj2getParam(values)
            this.props.formSubmit(values);
            this.getOrderSummary(values);
        });
    }

    componentWillMount() {
        let locale=sessionManager.get('locale');
        this.state.searchQuest = `${qs.stringify(this.props.params)}&locale=${locale}`;
        this.getStuGroup();
        this.getOrderSummary();
    }

    componentDidMount(){
        this.hideFormItem(this.state.hideFlag)
    }
    changeFlag = () => {
        this.setState({
            hideFlag: !this.state.hideFlag
        },()=>{this.hideFormItem(this.state.hideFlag)})
    }

    hideFormItem=(flag)=>{
        this.formItem = document.querySelector('.ant-row-flex');
        if (this.lessXXl) {
            Array.from(this.formItem.children).map((k, v, arr) => {
                if(v>arr.length-10&&v!=arr.length-1)
                    flag?k.classList.add('hide'):k.classList.remove('hide');
                if(v==arr.length-1){
                    if(flag){
                        k.classList.remove('ant-col-xl-10');
                        k.classList.add('ant-col-xl-24');
                    }
                }
            })
        }
    }

    getOrderSummary = (data = this.props.params) => {
        axios.post('/api/order/summary/get', {...data}).then(res => {
            if (res&&res.data) {
                this.setState(Object.assign(this.state.orderSummary, res.data));
            }
        })
    }

    getStuGroup = () => {
        axios.post('/api/stubGroup/listForOption/qry', {}).then(res => {
            if (res && res.data) {
                this.setState({stubGroup: res.data})
            }
        })
    }


    render() {
        const token=(JSON.parse(sessionStorage.getItem("token"))||{}).token;
        const {getFieldDecorator} = this.props.form;
        const dateFormat = 'YYYY.MM.DD HH:mm:ss';
        //下拉框校验
        const config = {
            rules: [{validator: this.endTimeLess}],
            initialValue: [moment(this.props.params.chargeEndTimeStart, dateFormat), moment(this.props.params.chargeEndTimeEnd, dateFormat)]
        };
        const gridStyle = {
            width: '20%',
            textAlign: 'center',
            marginBottom: '40px',
            display: 'inline-block'
        };
        const common = this.props.intl.messages.common;
        const validFlag=[
            {name:common.valid,key:1},
            {name:common.Invalid,key:2}
        ];
        return (
            <div>
                <form form={this.props.form} className={'SC-form'}>
                    <Row gutter={24} type="flex">
                        <Col xxl={7} xl={12}>
                            <FormItem
                                label={common.orderGenerationTime}
                            >
                                {getFieldDecorator('chargeStartTime', config)(
                                    <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" style={{width:'100%'}}/>
                                )}
                            </FormItem>
                        </Col>
                        <Col xxl={5} xl={7}>
                            <FormItem
                                label={common.selectPlant}
                            >
                                {getFieldDecorator(`stubGroupId`,)(
                                    <SCSelect style={{maxWidth:180}} url={()=>{return axios.get("/api/stubGroup/listForOption/addSettlement/qry")}} />
                                )}
                            </FormItem>
                        </Col>
                        <Col xxl={4} xl={5}>
                            <FormItem
                                label={common.EquipmentNo}
                            >
                                {getFieldDecorator('stubId')(
                                    <Input />
                                )}
                            </FormItem>
                        </Col>
                        <Col xxl={4} xl={5}>
                            <FormItem
                                label={common.chargeUser}
                            >
                                {getFieldDecorator('account')(
                                    <Input />
                                )}
                            </FormItem>

                        </Col>
                        <Col xxl={4} xl={7}>
                            <FormItem
                                label={common.orderNO}
                            >
                                {getFieldDecorator('chargeId')(
                                    <Input />
                                )}
                            </FormItem>
                        </Col>
                        <Col xxl={4} xl={7}>
                            <FormItem
                                label={common.vinOfCar}
                            >
                                {getFieldDecorator('vin')(
                                    <Input />
                                )}
                            </FormItem>
                        </Col>
                        <Col xxl={4} xl={5}>
                            <FormItem
                                label={common.licenseNumber}
                            >
                                {getFieldDecorator('plateNo')(
                                    <Input />
                                )}
                            </FormItem>
                        </Col>
                        <Col xxl={4} xl={6}>
                            <FormItem
                                label={common.chargeMode}
                            >
                                {getFieldDecorator('startType')(
                                    <Select  style={{fontSize:12}} allowClear={true}>
                                        {
                                            startTypeJSON.map((item) =>
                                                <Option value={item.id} key={item.id}>{item.name}</Option>
                                            )
                                        }
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col xxl={4} xl={6}>
                            <FormItem
                                label={common.chargingState}
                            >
                                {getFieldDecorator('status')(
                                    <Select allowClear={true}>
                                        <Option value="1">{common.charging}</Option>
                                        <Option value="9">{common.chargingCompleted}</Option>
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col xxl={4} xl={5}>
                            <FormItem
                                label={common.orderState}
                            >
                                {getFieldDecorator('validFlag',{
                                    initialValue:1
                                })(
                                    <Select allowClear={true}>
                                        {
                                            validFlag.map((item)=>
                                                <Option value={item.key} key={item.key}>{item.name}</Option>
                                            )
                                        }
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                        <Col xxl={4} xl={7}>
                            <FormItem
                                label={'部门'}
                            >
                                {getFieldDecorator('org')(
                                    <DepartmentPicker/>
                                )}
                            </FormItem>
                        </Col>
                        <Col xxl={24} xl={24} style={{ textAlign: 'right' }}>
                            <FormItem>
                                <Button className="ant-btn-84" onClick={this.handleReset}>{common.clear}</Button>
                                <Button type="primary" style={{marginRight:8}} className="ant-btn-84" onClick={this.handleSubmit}>{common.search}</Button>
                                <a href={`${axios.defaults.baseURL}/api/order/list/export?${this.state.searchQuest}&token=${token}`}>
                                    <Button type="primary"  className="ant-btn-84" style={{marginRight:8}}>{common.exportStatement}</Button>
                                </a>
                                {this.lessXXl&&<Button className="ant-btn-84" type="primary" onClick={this.changeFlag}>
                                    {common.more}<Icon type={this.state.hideFlag ? 'down' : 'up'} />
                                </Button>}
                            </FormItem>
                        </Col>
                    </Row>
                </form>
                <div className="boxOuter">
                    <div className="box">
                        <div className="num">{this.state.chargeCnt}</div>
                        <div className="box-desc">{common.numberOfCharge}</div>
                    </div>
                    <div className="box">
                        <div className="num">{this.state.elecSum}</div>
                        <div className="box-desc">{common.chargingAmount}</div>
                    </div>
                    <div className="box">
                        <div className="num">{this.state.chargeTimeSum}</div>
                        <div className="box-desc">{common.chargingTime}</div>
                    </div>
                    <div className="box">
                        <div className="num">{this.state.elecFeeSum}</div>
                        <div className="box-desc">{common.electricityAmount}</div>
                    </div>
                    <div className="box">
                        <div className="num">{this.state.serviceFeeSum}</div>
                        <div className="box-desc">{common.ServiceAmount}</div>
                    </div>
                </div>
            </div>
        )
    }
}

//ant 表格验证需要创建表格-createForm
innerEnterpriseForm = createForm()(innerEnterpriseForm);
export default injectIntl(innerEnterpriseForm);